<template>
  <Top-Page class="live-box">
    <!-- #ifndef APP -->
    <view class="H5-live" id="player_bridging" ref="refH5Live"></view>
    <!--#endif  -->

    <!-- #ifdef APP -->
    <NavBar title="直播" left-arrow @click-left="navBack()" />

    <view style="display: flex; width: 100%">
      <view
        v-if="query.status != 0"
        class="tab-select-item"
        :style="{ 'background-color': '#A8D6F8' }"
        @click="toLiveRoom"
      >
        开播
      </view>
      <view
        class="tab-select-item"
        :style="{ 'background-color': playType === 0 ? '#2B98F0' : '#A8D6F8' }"
        @click="playType = 0"
      >
        直播
      </view>
      <view
        class="tab-select-item"
        :style="{ 'background-color': playType === 1 ? '#2B98F0' : '#A8D6F8' }"
        @click="playType = 1"
      >
        回放
      </view>
    </view>

    <view class="live-fill-view">
      <!-- 直播UI -->
      <view v-show="playType === 0">
        <view class="field-box field-border">
          <view class="field-label">
            <view class="field-label__text">用户</view>
            <!-- <view>：</view> -->
          </view>

          <input
            disabled
            type="password"
            class="field-value"
            :value="liveInfo.userId"
            @input="
              (event) => {
                liveInfo.userId = event.detail.value;
              }
            "
            placeholder="请输入用户ID"
          />
        </view>

        <view class="field-box field-border">
          <view class="field-label">
            <view class="field-label__text">房间号</view>
            <!-- <view>：</view> -->
          </view>

          <input
            class="field-value"
            :value="liveInfo.channelId"
            @input="
              (event) => {
                liveInfo.channelId = event.detail.value;
              }
            "
            placeholder="请输入频道ID"
          />
        </view>
        <!-- <input
          class="live-input"
          :value="liveInfo.appId"
          @input="
            (event) => {
              liveInfo.appId = event.detail.value;
            }
          "
          placeholder="请输入App ID"
        /> -->
        <!-- <input
          class="live-input"
          :value="liveInfo.appSecret"
          @input="
            (event) => {
              liveInfo.appSecret = event.detail.value;
            }
          "
          placeholder="请输入App Secret"
        /> -->
      </view>
      <!-- 回放UI -->
      <view v-show="playType === 1">
        <view class="field-box field-border">
          <view class="field-label">
            <view class="field-label__text">用户</view>
            <!-- <view>：</view> -->
          </view>

          <input
            disabled
            type="password"
            class="field-value"
            :value="playbackInfo.userId"
            @input="
              (event) => {
                playbackInfo.userId = event.detail.value;
              }
            "
            placeholder="请输入用户ID"
          />
        </view>

        <view class="field-box field-border">
          <view class="field-label">
            <view class="field-label__text">App ID</view>
            <!-- <view>：</view> -->
          </view>
          <input
            disabled
            type="password"
            class="field-value"
            :value="playbackInfo.appId"
            @input="
              (event) => {
                playbackInfo.appId = event.detail.value;
              }
            "
            placeholder="请输入App ID"
          />
        </view>
        <view class="field-box field-border">
          <view class="field-label">
            <view class="field-label__text">App Secret</view>
            <!-- <view>：</view> -->
          </view>
          <input
            disabled
            type="password"
            class="field-value"
            :value="playbackInfo.appSecret"
            @input="
              (event) => {
                playbackInfo.appSecret = event.detail.value;
              }
            "
            placeholder="请输入App Secret"
          />
        </view>

        <view class="field-box field-border">
          <view class="field-label">
            <view class="field-label__text">房间号</view>
            <!-- <view>：</view> -->
          </view>
          <input
            class="field-value"
            :value="playbackInfo.channelId"
            @input="
              (event) => {
                playbackInfo.channelId = event.detail.value;
              }
            "
            placeholder="请输入频道ID"
          />
        </view>

        <view class="field-box field-border">
          <view class="field-label">
            <view class="field-label__text">视频Vid</view>
            <!-- <view>：</view> -->
          </view>
          <input
            class="field-value"
            :value="playbackInfo.vid"
            @input="
              (event) => {
                playbackInfo.vid = event.detail.value;
              }
            "
            placeholder="请输入视频Vid"
          />
        </view>

        <view class="uni-list-cell uni-list-cell-pd">
          <view class="uni-list-cell-db">点播列表</view>
          <switch
            @change="
              (event) => {
                isVideoList = event.detail.value ? 1 : 0;
              }
            "
          />
        </view>
      </view>
    </view>

    <view class="types">
      <view
        class="types-item"
        :style="{ 'background-color': sceneType === 1 ? '#2B98F0' : '#A8D6F8' }"
        @click="sceneType = 1"
      >
        云课堂场景
      </view>
      <view
        class="types-item"
        :style="{ 'background-color': sceneType === 2 ? '#2B98F0' : '#A8D6F8' }"
        @click="sceneType = 2"
      >
        直播带货场景
      </view>
    </view>

    <button type="primary" class="primary" @click="setUserInfo">登录</button>
    <!--#endif  -->
  </Top-Page>
</template>

<script>
// #ifdef APP
var playModule = uni.requireNativePlugin('PLV-LiveUniPlugin-WatchPlayModule');
var configModule = uni.requireNativePlugin('PLV-LiveUniPlugin-WatchConfigModule');
// #endif

// #ifndef APP
// import { createWatchCore, PolyvWatchCoreEvents } from '@polyv/live-watch-sdk';
// #endif

import NavBar from '@/components/NavBar/NavBar.vue';
import { navBack } from '@/utils/utils.js';

const playConfig = {
  userId: '',
  appId: '',
  appSecret: ''
};

export default {
  data() {
    return {
      navBack: navBack,
      query: {},
      sceneType: 1, //场景类型 1云课堂场景, 2直播带货场景
      playType: 0, //播放类型 0直播，1回放
      isVideoList: 0, //回放中是否进入回放列表0回放视频 1回放列表
      liveInfo: {
        channelId: '',
        userId: playConfig.userId,
        appId: playConfig.appId,
        appSecret: playConfig.appSecret
      },
      playbackInfo: {
        channelId: '',
        userId: playConfig.userId,
        appId: playConfig.appId,
        appSecret: playConfig.appSecret,
        vid: ''
      }
    };
  },
  components: { NavBar },
  onLoad(options) {
    Object.assign(this.query, options);

    const data = {
      channelId: options.channel_id,
      userId: options.userID,
      appId: options.app_id,
      appSecret: options.app_secret
    };
    Object.assign(this.liveInfo, data);
    Object.assign(this.playbackInfo, data);

    // #ifdef APP
    //配置观众信息
    this.setViewerInfo(options);

    //配置跑马灯信息
    this.setMarqueeConfig();

    //设置iPad全屏配置
    this.setFullScreenButtonShow();
    // #endif

    // #ifndef APP
    this.H5LiveInit(options);
    // #endif
  },
  methods: {
    async H5LiveInit(options) {
      const watchCore = createWatchCore({
        channelId: options.channel_id, // 传入观看页的频道号
        userInfo: {
          userId: options.imUserID,
          nick: options.realname,
          pic: decodeURIComponent(options.avatar),
          actor: ''
        }
      });

      // 监听 setup 钩子
      watchCore.eventEmitter.on(PolyvWatchCoreEvents.WatchCoreSetuped, () => {
        console.info('观看页核心实例安装完成');
      });

      // 安装核心实例
      await watchCore.setup();

      // 互动 SDK
      watchCore.interactReceive.setupIarCore();

      const supportResult = watchCore.player.supportLowLatency();
      let lowLatency = true;
      if (supportResult.support) {
        lowLatency = true;
      } else {
        lowLatency = false;
      }

      //播放器 SDK
      await watchCore.player.setupPlayer({
        container: this.$refs.refH5Live.$el,
        lowLatency: lowLatency, // 使用无延迟播放
        autoChangePlayback: false,
        autoplay: true,
        barrageEnabled: true,
        showController: true,
        fullScreenMode: true
      });

      watchCore.player.bindSocketEvents();

      // 连接聊天室进入直播观看页
      await watchCore.connect();
    },
    toLiveRoom() {
      uni.navigateTo({
        url: '/pages/live/live-room/live-room'
      });
    },
    setViewerInfo(options) {
      configModule.setViewerInfo(
        {
          viewerId: options.imUserID,
          viewerName: options.realname,
          viewerAvatar: decodeURIComponent(options.avatar)
        },
        (result) => {
          // uni.showToast({
          // 	title: result.isSuccess ? 'setViewerInfo succeed' : result.errMsg,
          // 	icon: 'none'
          // });
        }
      );
    },
    //配置跑马灯信息
    setMarqueeConfig() {
      configModule.setMarqueeConfig(
        {
          code: ''
        },
        (result) => {
          // title: result.isSuccess ? 'setMarqueeConfig succeed' : result.errMsg,

          !result.isSuccess &&
            uni.showToast({
              title: result.errMsg,
              icon: 'none'
            });
        }
      );
    },
    // 设置多场景的账号属性
    setUserInfo() {
      uni.showToast({
        title: '登陆中...',
        icon: 'loading',
        mask: true,
        duration: 999999
      });

      var configInfo = this.playType === 0 ? this.liveInfo : this.playbackInfo;
      var that = this;
      configModule.setConfig(
        {
          appId: configInfo.appId,
          userId: configInfo.userId,
          appSecret: configInfo.appSecret
        },
        (result) => {
          if (result.isSuccess) {
            that.startLive();
          } else {
            uni.showToast({
              title: result.errMsg,
              icon: 'none'
            });
          }
        }
      );
    },
    // 设置iPad 上是否显示全屏按钮（仅在iPad上生效）
    setFullScreenButtonShow() {
      let platform = uni.getSystemInfoSync().platform;
      if (platform == 'ios') {
        playModule.showFullScreenButtonOnIPad({
          show: true
        });
      }
    },
    startLive() {
      console.log('Start live  ' + JSON.stringify(this.liveInfo));
      if (this.playType === 0) {
        // 直播
        playModule.loginLiveRoom(
          this.sceneType,
          {
            channelId: this.liveInfo.channelId
          },
          (result) => {
            uni.hideToast();
            // title: result.isSuccess ? 'login succeed' : result.errMsg,
            !result.isSuccess &&
              uni.showToast({
                title: result.errMsg,
                icon: 'none'
              });
          }
        );
      } else if (this.playType === 1) {
        // 回放
        playModule.loginPlaybackRoom(
          this.sceneType,
          {
            channelId: this.playbackInfo.channelId,
            videoId: this.playbackInfo.vid,
            vodType: this.isVideoList
          },
          (result) => {
            uni.hideToast();
            // title: result.isSuccess ? 'login succeed' : result.errMsg,
            !result.isSuccess &&
              uni.showToast({
                title: result.errMsg,
                icon: 'none'
              });
          }
        );
      }
    }
  }
};
</script>

<style lang="scss">
.live-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding: 100rpx 0;

  .tab-select-view {
    display: flex;
    width: 100%;
  }

  .tab-select-item {
    flex: 0.5;
    padding: 20rpx 0;
    text-align: center;
    color: white;
  }

  .types {
    display: flex;
    width: 80%;
    margin-top: 0.625rem;
    justify-content: space-around;

    .types-item {
      font-size: 24rpx;
      line-height: 1.2;
      padding: 12rpx 30rpx;
      border-radius: 99rpx;
      text-align: center;
      color: white;
    }
  }

  .live-fill-view {
    padding: 10rpx 0;
    width: 80%;
    margin-top: 60rpx;
    padding: 0 20rpx;
    background-color: #fff;
    border-radius: 20rpx;
    box-shadow: 2rpx 2rpx 16rpx #ddd;
  }

  .live-input {
    min-height: 35px;
    height: 35px;
    border-bottom: 1px solid #cccccc;
    font-size: 14px;
    padding: 0 20rpx;
    margin-top: 10rpx;
  }
  .uni-list-cell {
    position: relative;
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -webkit-flex-direction: row;
    flex-direction: row;
    -webkit-box-pack: justify;
    -webkit-justify-content: space-between;
    justify-content: space-between;
    -webkit-box-align: center;
    -webkit-align-items: center;
    align-items: center;
    padding: 20rpx 0;
  }
  .uni-list-cell::after {
    position: absolute;
    z-index: 3;
    right: 0;
    bottom: 0;
    left: 15px;
    height: 1px;
    content: '';
    -webkit-transform: scaleY(0.5);
    transform: scaleY(0.5);
    background-color: #c8c7cc;
  }

  .field-box {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
    padding: 30rpx 10rpx;

    .field-label {
      flex-shrink: 0;
      display: flex;
      flex-direction: row;
      align-items: center;

      .field-label__text {
        width: 120rpx;
      }
    }

    .field-value {
      width: 100%;
      font-size: 14px;
      display: flex;
      align-items: center;
    }
  }

  .field-border {
    border-bottom: 1rpx solid #f4f4f4;
  }

  .primary {
    margin-top: 100rpx;
    line-height: 2.4;
    width: 80%;
  }

  .uni-input-input:disabled {
    color: #2b98f0;
  }
}

.H5-live {
  position: fixed;
  width: 100vh;
  height: 100vw;
  z-index: 1000;
  top: 50%;
  bottom: 0 !important;
  left: 50%;
  transform: translate(-50%, -50%) rotate(90deg);
}
</style>
